// pages/mine/order/detail/detail.js
const utils = require('../../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: null,
    surplus: '00:00:00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    let id = options.id;
    utils.requests({
      url: 'order/read/'+id,
      success: function(data) {
        if ( data.data.code == 200 ) {
          _this.setData({
            data: data.data.data
          })
          if ( data.data.data.payment_status == 0 ) {
            let create_date = new Date(data.data.data.create_at);
            let create_time = Date.parse(create_date)/1000+60*30;
            let setTime = setInterval(function(){
              let current_time = Date.parse(new Date())/1000;
              let time = create_time-current_time;
              if ( _this.data.data.payment_status != 0 ) {
                clearInterval(setTime);
                return false;
              }
              if ( time <= 0 ) {
                cancel(_this);
                clearInterval(setTime);
                return false;
              }
              let minute = parseInt(time/60);
              let second = parseInt(time%60);
              _this.setData({
                surplus: '00:'+(minute.toString().length>1?'':'0')+minute+':'+(second.toString().length>1?'':'0')+second
              })
            }, 1000);
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 取消订单
  btnCancel: function(){
    let _this = this;
    cancel(_this);
  },

  // 页面跳转
  jump: function(e) {
    let _this = this;
    let url = e.currentTarget.dataset.url;
    let id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: url+(id>0?'?id='+id:''),
    })
  },

})

let cancel = (_this) => {
  utils.requests({
    url: 'order/cancel/'+_this.data.data.id,
    success: function(data){
      if ( data.data.code == 200 ) {
        let res = _this.data.data;
        res.payment_status = 2;
        res.payment_status_text = '已取消'
        _this.setData({
          data: res
        });
      }
    }
  })
}